<?php

namespace App\Http\Controllers;

use App\Http\Requests\ExportKeywordSearchRequest;
use App\Services\KeywordSearchService;
use App\Services\MerchantService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Jiannei\Response\Laravel\Support\Facades\Response;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class KeywordSearchController extends Controller
{
    /**
     * Get keyword search list
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $perPage = $request->query('perPage', 10);
            $data = KeywordSearchService::getList($perPage);
            return Response::success($data);
        } catch (\Exception $e) {
            return Response::fail($e->getMessage());
        }
    }

    /**
     * Show keyword search
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function show(Request $request, int $id): JsonResponse
    {
        try {
            $data = MerchantService::getMerchantsByKeywordSearchId($id);
            return Response::success($data);
        } catch (\Exception $e) {
            return Response::fail($e->getMessage());
        }
    }

    /**
     * Export keyword search
     * @param ExportKeywordSearchRequest $request
     * @return JsonResponse|BinaryFileResponse
     */
    public function export(ExportKeywordSearchRequest $request): BinaryFileResponse|JsonResponse
    {
        try {
            $params = $request->only('id');
            $data = MerchantService::getMerchantsByKeywordSearchId($params['id']);
            $spreadSheet = new Spreadsheet();
            $sheet = $spreadSheet->getActiveSheet();
            $header  = ["A1"=>"地图", "B1"=>"商家名称", "C1"=>"商家电话", "D1"=>"商家地址", "E1"=>"省份", "F1"=>"城市", "G1"=>"区域"];
            foreach ($header as $k=>$title) {
                $sheet->setCellValue($k, $title);
            }

            $num = 2;
            foreach ($data as $i => $v) {
                $rowCell = $num + $i;
                $sheet->setCellValue("A".$rowCell, $v->map);
                $sheet->setCellValue("B".$rowCell, $v->title);
                $sheet->setCellValue("C".$rowCell, $v->tel);
                $sheet->setCellValue("D".$rowCell, $v->address);
                $sheet->setCellValue("E".$rowCell, $v->province);
                $sheet->setCellValue("F".$rowCell, $v->city);
                $sheet->setCellValue("G".$rowCell, $v->district);
            }

            $writer = new Xlsx($spreadSheet);
            $writer->setUseDiskCaching(true);
            $writer->save('merchants.xlsx');
            return response()->download('merchants.xlsx');
        } catch (\Exception $e) {
            return Response::fail($e->getMessage());
        }
    }
}
